import type { SimpleRegion } from '@/apis/model/region.ts'
import { getManageRegionsListApi } from '@/apis/modules/node'

interface HookOptions {
  after?: (regions: Array<SimpleRegion>) => void
}

const regions = ref<Array<SimpleRegion>>([])
const loading = ref(false)

// 区域
export function useRegions(options?: HookOptions) {
  const { parse } = useLangField()
  function getRegions() {
    if (!options?.after && (loading.value || regions.value.length)) {
      return
    }

    loading.value = true
    // debugger
    getManageRegionsListApi({
      limit: 500,
    })
      .then((res) => {
        regions.value = res.list as Array<SimpleRegion>
        options?.after?.(regions.value)
      })
      .finally(() => {
        loading.value = false
      })
  }

  function format(region: SimpleRegion) {
    const field = parse(region.name || '')
    return {
      label: field?.['zh-CN'] || '-',
      value: String(region.id),
    }
  }

  // 所有区域
  const allRegionOptions = computed<Array<OptionItem>>(() => {
    return regions.value.map(item => format(item))
  })

  onMounted(getRegions)

  return { allRegionOptions, regions }
}
